<template>
  <nav>
    <div class="NavBar">
      <div class="left-buttons">

        <!-- 返回主页 -->
        <el-tooltip content="首页" effect="light">
          <el-button type="warning" round @click="goToHomepage">
            <el-icon>
              <HomeFilled />
            </el-icon>
          </el-button>
        </el-tooltip>

        <!-- 返回上一页 -->
        <el-tooltip v-if="!(['/', '/homepage', '/login'].includes($route.path))" content="返回" effect="light">
          <el-button type="warning" round @click="goBack">
            <el-icon>
              <ArrowLeft />
            </el-icon>
          </el-button>
        </el-tooltip>

      </div>

      <div class="right-buttons">

        <!-- 个人中心 -->
        <el-tooltip v-if="!(['/personal-center', '/login'].includes($route.path))" content="个人中心" effect="light">
          <el-button type="warning" round @click="goToPersonalCenter">
            <el-icon>
              <UserFilled />
            </el-icon>
          </el-button>
        </el-tooltip>

        <!-- 退出登录 -->
        <el-tooltip v-else-if="$route.path !== '/login'" content="退出登录" effect="light">
          <el-button type="warning" round @click="open">
            <el-icon>
              <SwitchButton />
            </el-icon>
          </el-button>
        </el-tooltip>

        <!-- 消息抽屉 -->
        <el-tooltip content="我的消息" effect="light">
          <el-button type="warning" round @click="showDrawer">
            <el-icon>
              <Message />
            </el-icon>
          </el-button>
        </el-tooltip>
      </div>
    </div>

    <el-drawer v-model="drawer" title="消息" :with-header="true" :before-close="handleBeforeClose" :lock-scroll=true>

      <el-scrollbar>
        <el-card shadow="hover" v-if="messageList.length === 0" class="message-card">
          <p>
            暂无消息哦
          </p>
        </el-card>

        <el-timeline v-else style="max-width: 600px">

          <el-pagination @current-change="pageFeed" :current-page="current" :page-size=size pager-count="5"
            layout="prev, pager, next,total" :total="total">
          </el-pagination>

          <el-divider />

          <el-timeline-item center v-for="message in messageList" :key="message.messageId" placement="top"
            :timestamp="message.sentTime">
            <el-card shadow="hover" @click="navigateToClub(message)" class="message-card">

              <!-- 消息标题 -->
              <template #header>
                <div class="card-header">
                  <el-avatar :size="30" :src="message.logoUrl" />
                  <span>{{ message.clubName }}</span>
                </div>
              </template>

              <!-- 消息内容 -->
              <p class="card-content">
                {{ message.messageContent }}
              </p>
            </el-card>


          </el-timeline-item>
        </el-timeline>
      </el-scrollbar>
    </el-drawer>
  </nav>
</template>

<script>
import { ref } from 'vue'
import { ArrowLeft, HomeFilled, Message, UserFilled, SwitchButton } from '@element-plus/icons-vue'
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';

export default {

  components: {
    HomeFilled,
    ArrowLeft,
    Message,
    UserFilled,
    SwitchButton
  },
  data() {
    return {
      user: {},
      drawer: ref(false),
      token: "0",
      messageList: [],
      total: 0,
      size: 5,
      current: 1,
      pages: 1,
      alreadyObtained: false
    }
  },

  methods: {

    open() {
      ElMessageBox.confirm(
        '你确认退出登录吗?',
        {
          confirmButtonText: 'YES',
          cancelButtonText: 'NO',
          center: true,
          roundButton: true
        }
      )
        .then(() => {
          this.logout();
        })
        .catch(() => {

        })
    },

    getMyInfo() {
      axios
        .get("/user/myInfo")
        .then(response => {
          this.user = response.data.data;
        })
        .catch(error => {
          console.log(error);
        })
    },

    goToHomepage() {
      this.$router.push({ name: "Homepage" });
    },
    goToPersonalCenter() {
      axios.get("/user/getUserType").then(response => {
        if (response.data.data === "系统管理员") {
          this.$router.push('/club-audit');
        }
        else {
          this.$router.push({ name: "PersonalCenter" });
        }
      }).catch(error => {
        console.error("Error:", error);
      });

    },

    navigateToClub(message) {

      const clubId = message.clubId;

      this.drawer = false;

      this.$router.push({ name: "ClubDetail", query: { clubId: clubId } });
    },

    showDrawer() {
      this.drawer = true;
      const nowToken = sessionStorage.getItem('token')

      if (nowToken != null && nowToken !== this.token) {
        // this.getMyInfo();
        this.getMessage();
      } else {

        setTimeout(() => {
          this.drawer = false;
        }, 1500)

        ElMessage({
          message: '请先进行登录哦',
          showClose: true,
          type: 'error',
        })
        this.messageList = []
        
      }
    },
    handleBeforeClose(done) {
      this.current = 1;
      done(); // 调用done()来确认关闭动作
    },
    getMessage() {
      let params = {
        pageNum: this.current,
        pageSize: 5
      }
      axios
        .get("/message/checkMassages", { params })
        .then(response => {
          ElMessage({
            message: '消息获取成功',
            showClose: true,
            type: 'success',
          })

          this.total = response.data.data.total;
          this.size = response.data.data.size;
          this.current = response.data.data.current;
          this.pages = response.data.data.pages;

          this.messageList = response.data.data.records;


        })
        .catch(error => {
          console.log(error);
        })
    },

    pageFeed(newPageNum) {

      if (newPageNum == this.current) {
        return;
      }

      this.current = newPageNum;
      this.getMessage();
    },
    logout() {
      // 在这里实现退出登录的逻辑
      console.log("用户退出登录");

      sessionStorage.removeItem("token");
      sessionStorage.removeItem("studentId");

      ElMessage.success('退出登录成功');
      this.$router.push({ name: "Homepage" });
    },
    goBack() {
      this.$router.go(-1)
    }
  },
};
</script>

<style scoped>
.NavBar {
  background-color: #ffbf6b;
  /* background: linear-gradient(180deg, #ffbf6b, #ffe0b2);  */
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  opacity: 0.8;
  border-radius: 5px;
}

.left-buttons,
.right-buttons {
  display: flex;
  gap: 10px;
  /* 按钮之间的间距 */
}

.el-pagination {
  display: flex;
  justify-content: center;
  margin: 20px;
}

.message-card {
  height: 20%;
  align-items: center;
  cursor: pointer;
}

.card-header {
  gap: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.card-content {
  text-align: left;
  font-size: 14px;
}

::v-deep(.el-button) {
    font-size: 18px;
  }

</style>
